<?php
/*

直接拿货升级：阶梯

本身是代理级别：推荐会员与自己平级，数量达标升级

价格体系：不同级别折扣不同，代理算差价提成

单个产品出售时使用八级分销：按三级分销算法计算分成


*/
class RangeEHNlevel{
	public $money;
	public $order;
	public $site_id;
	public $userlist;
	public $orderdb;
	public $memberdb;
	public $member_id;
	public $error = array();
	//构造函数
	public function RangeEHNlevel($order_id = 0, $site_id = 0, $member_id = 0){
		$this->memberdb = D('Member');
		$this->orderdb = D('Order');
		$this->saledb = M('Sale');
		$this->money = $this->getmoney();
		$this->site_id = $site_id;
		
		$db = M('Affiliatesetting');
		$affsetting = $db -> where(array('site_id' => $this->site_id,'classname' => 'RangeEHNlevel')) -> find();
		$this -> affsettingarr = unserialize($affsetting['value']);
		
		$this->order = $this->orderdb -> where(array('id' => $order_id)) -> find();
		
		$this->member_id = $member_id > 0? $member_id: $this->order['member_id'];
		if(!$this->order){
			$this->error['info'] = '订单不存在！';
		}
		 
		$this->updateUserLevel();
	}
	//创建设置项表单
	public function createform(){
		
		$db = M('Affiliatesetting');
		
		$ret = array ('levelname' => array ( 0 => '股东商', 1 => '渠道商', 2 => '代理商', 3 => '分销商', ), 'levelbuy' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ), 'levelaff' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ), 'levelaff_' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ), 'rlevel' => array ( 0 => '0', 1 => '0', 2 => '0', 3 => '0', ),'level' => array ( 0,0,0,0,0,0,0,0 ),'levelnamebase' => 'VIP会员', 'changelevel' => '恭喜您升级成为：@levelname@');
		
		
		
		$ret = $db -> where(array('site_id' => $this->site_id,'classname' => 'RangeEHNlevel')) -> find();
		$ret = unserialize($ret['value']);
		//F('ret',$ret);
		$html = '<style>#RangeEHNlevel td{padding:5px;}</style><table id="RangeEHNlevel" border="1" cellspacing="0" cellpadding="5" width="100%">
  <tr>
    <th align="center" style="text-align:center; width:100px;">级别</th>
	<th align="center" style="text-align:center;">级别名称</th>
	<th align="center" style="text-align:center;">购买指定产品(条件A,填写商品ID)</th>
	<th align="center" style="text-align:center;">直推平级人数(条件B)</th> 


  </tr>
  <tr>
    <td align="center" valign="middle">国代</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][0].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][0].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff[]" value="'.$ret['levelaff'][0].'" /></td>


  </tr>
  <tr>
    <td align="center" valign="middle">省代</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][1].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][1].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff[]" value="'.$ret['levelaff'][1].'" /></td>


  </tr>
  <tr>
    <td align="center" valign="middle">市代</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][2].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][2].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelaff[]" value="'.$ret['levelaff'][2].'" /></td>


  </tr>
  <tr>
    <td align="center" valign="middle">县代</td>
	<td align="center" valign="middle"><input type="text" name="levelname[]" value="'.$ret['levelname'][3].'" /></td>
	<td align="center" valign="middle"><input type="text" name="levelbuy[]" value="'.$ret['levelbuy'][3].'" /></td>
<td align="center" valign="middle"><input type="text" name="levelaff[]" value="'.$ret['levelaff'][3].'" /></td>


  </tr>
  
<tr>
    
    <td align="left" colspan="5">
	当推荐人的等级高于消费者等级时，推荐人拿差价佣金。<br>

	条件A、B同时满足才升级 <input type="text" name="levelupand" value="'.$ret['levelupand'].'" /> （1是，0否）</td>
  </tr>
<tr>
    
    <td align="left" colspan="5">
	消费金额是否为累计<br>

	 <input type="text" name="totalsumtype" value="'.$ret['totalsumtype'].'" /> （1是，0否）</td>
  </tr>
</table>
<br>

<table cellpadding="0" class="Threelevel" cellspacing="0" border="1" width="100%">








<tr>
    <td align="center" valign="middle" style="width:150px;">分销资格等级名称</td>
    <td align="left" colspan="2"><input type="text" name="levelnamebase" value="'.$ret['levelnamebase'].'" /></td>
  </tr>
  
  
  <tr>
    <td align="center" valign="middle" style="width:150px;">会员升级后通知信息</td>
    <td align="left" colspan="2"><input style="width:100%" type="text" name="changelevel" value="'.$ret['changelevel'].'" /><br>
等级名称@levelname@
</td>
  </tr>
  
  
  <tr>
    <td align="center" valign="middle" style="width:150px;">分销资格最低消费</td>
    <td align="left" colspan="2"><input type="text" name="levelmoney" value="'.$ret['levelmoney'].'" /></td>
  </tr>
  <tr>
    <td align="center" valign="middle" style="width:150px;">会员消费提点（1启用，0禁用）</td>
    <td align="left" colspan="2"><input type="text" name="VIPaff" value="'.$ret['VIPaff'].'" /></td>
  </tr>
  <tr>
    <td align="center" valign="middle" style="width:150px;">购买特定商品升级(商品ID)</td>
    <td align="left" colspan="2"><input type="text" name="product_id" value="'.$ret['product_id'].'" />填写0则不生效，依然使用最低消费额度升级</td>
  </tr>
</table>
<br>

<style>.Threelevel td{padding:5px;}</style><table class="Threelevel" border="1" cellspacing="0" cellpadding="5" width="100%">
 <tr>
    <th align="center" style="text-align:center; width:100px;">级别</th>
    <th align="center" style="text-align:center;">VIP会员分成比例</th>
	<th align="center" style="text-align:center;">县代分成比例</th>
	<th align="center" style="text-align:center;">市代分成比例</th>
	<th align="center" style="text-align:center;">省代分成比例</th>
	<th align="center" style="text-align:center;">国代分成比例</th>
  </tr>
  
  <tr>
    <td align="center" valign="middle">1</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][0].'" />%</td>
	<td align="center"><input type="text" name="xlevel[]" value="'.$ret['xlevel'][0].'" />%</td>
	
	 <td align="center"><input type="text" name="clevel[]" value="'.$ret['clevel'][0].'" />%</td>
	 <td align="center"><input type="text" name="plevel[]" value="'.$ret['plevel'][0].'" />%</td>
	 <td align="center"><input type="text" name="glevel[]" value="'.$ret['glevel'][0].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">2</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][1].'" />%</td>
	<td align="center"><input type="text" name="xlevel[]" value="'.$ret['xlevel'][1].'" />%</td>
	
	 <td align="center"><input type="text" name="clevel[]" value="'.$ret['clevel'][1].'" />%</td>
	 <td align="center"><input type="text" name="plevel[]" value="'.$ret['plevel'][1].'" />%</td>
	 <td align="center"><input type="text" name="glevel[]" value="'.$ret['glevel'][1].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">3</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][2].'" />%</td>
	<td align="center"><input type="text" name="xlevel[]" value="'.$ret['xlevel'][2].'" />%</td>
	
	 <td align="center"><input type="text" name="clevel[]" value="'.$ret['clevel'][2].'" />%</td>
	 <td align="center"><input type="text" name="plevel[]" value="'.$ret['plevel'][2].'" />%</td>
	 <td align="center"><input type="text" name="glevel[]" value="'.$ret['glevel'][2].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">4</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][3].'" />%</td>
	<td align="center"><input type="text" name="xlevel[]" value="'.$ret['xlevel'][3].'" />%</td>
	
	 <td align="center"><input type="text" name="clevel[]" value="'.$ret['clevel'][3].'" />%</td>
	 <td align="center"><input type="text" name="plevel[]" value="'.$ret['plevel'][3].'" />%</td>
	 <td align="center"><input type="text" name="glevel[]" value="'.$ret['glevel'][3].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">5</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][4].'" />%</td>
	<td align="center"><input type="text" name="xlevel[]" value="'.$ret['xlevel'][4].'" />%</td>
	
	 <td align="center"><input type="text" name="clevel[]" value="'.$ret['clevel'][4].'" />%</td>
	 <td align="center"><input type="text" name="plevel[]" value="'.$ret['plevel'][4].'" />%</td>
	 <td align="center"><input type="text" name="glevel[]" value="'.$ret['glevel'][4].'" />%</td>
  </tr>
  <tr>
    <td align="center" valign="middle">6</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][5].'" />%</td>
	
	 <td align="center"><input type="text" name="xlevel[]" value="'.$ret['xlevel'][5].'" />%</td>
	
	 <td align="center"><input type="text" name="clevel[]" value="'.$ret['clevel'][5].'" />%</td>
	 <td align="center"><input type="text" name="plevel[]" value="'.$ret['plevel'][5].'" />%</td>
	 <td align="center"><input type="text" name="glevel[]" value="'.$ret['glevel'][5].'" />%</td>
	
  </tr>
  <tr>
    <td align="center" valign="middle">7</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][6].'" />%</td>
	<td align="center"><input type="text" name="xlevel[]" value="'.$ret['xlevel'][6].'" />%</td>
	<td align="center"><input type="text" name="clevel[]" value="'.$ret['clevel'][6].'" />%</td>
	<td align="center"><input type="text" name="plevel[]" value="'.$ret['plevel'][6].'" />%</td>
	<td align="center"><input type="text" name="glevel[]" value="'.$ret['glevel'][6].'" />%</td>
	
  </tr>
  <tr>
    <td align="center" valign="middle">8</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret['level'][7].'" />%</td>
	
	<td align="center"><input type="text" name="xlevel[]" value="'.$ret['xlevel'][7].'" />%</td>
	
	<td align="center"><input type="text" name="clevel[]" value="'.$ret['clevel'][7].'" />%</td>
	
	<td align="center"><input type="text" name="plevel[]" value="'.$ret['plevel'][7].'" />%</td>
	
	<td align="center"><input type="text" name="glevel[]" value="'.$ret['glevel'][7].'" />%</td>
	
	
	
	
	
  </tr>
  <tr>
    <td align="left" colspan="6"><span style="color:#f00;">当推荐人的等级平级时，佣金使用八级分销计算，等级分成比例由以上设置生成(此处为平级奖)</span></td>
  </tr>
</table>';

        return $html;
	}
	
	//保存设置项
	public function saveform(){
		if(isset($_POST['level'])){
			$data['classname'] = 'RangeEHNlevel';
			$data['value'] = serialize($_POST);
			$data['site_id'] = $this->site_id;
			$db = M('Affiliatesetting');
			$pc = (float)$_POST['rlevel'][0];
			foreach($_POST['level'] as $v){
				$pc += (float)$v;
			}
			if($pc > 100){
				$this->error['info'] = '设置错误，分成比的和大于100！';
				return false;
			}
			//dump($data);
			$ret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> find();
			if($ret){
				$saveret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> data(array('value' => $data['value'])) -> save();
			}else{
				$saveret = $db -> data($data) -> add();
			}
			if($saveret){
				return true; 
			}else{
				$this->error['info'] = $db -> getLastSql();
				return false;
			}
			
		}
	}
	
	
	

	
	
	public function updateUserLevel(){
		$db = M('Affiliatesetting');
		$affsetting = $db -> where(array('site_id' => $this->site_id,'classname' => 'RangeEHNlevel')) -> find();
		$affsettingarr = unserialize($affsetting['value']);
		//查询用户
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		//升级为基本分销等级
		$rlevel = array(0,0);
		$total = (float)$this->orderdb -> where(array('member_id' => $this->member_id, 'status' => 2)) -> sum('total');
		$mylevel = 0;
		if($affsettingarr['levelmoney'] <= $total && $affsettingarr['product_id'] == 0){
		    //更新用户等级
			$mylevel = 1;
	    }
		//dump($affsettingarr);
		if($affsettingarr['product_id'] > 0){
		    //更新用户等级
			$sale = $this->saledb -> where("pay_status = 1 and member_id = '".$this->member_id."' and product_id = '".$affsettingarr['product_id']."' and order_id > 0 and (order_id = '".$this->order['id']."' or (product_id = '".$affsettingarr['product_id']."' and pay_status = 1))") -> find();
			if($sale){
				$mylevel = 1;
			}
			
			
			
			if($affsettingarr['totalsumtype'] == 1){
				$maxOrderTotal = $this->saledb -> where(array('pay_status' => 1, 'member_id' => $this->member_id, 'product_id' => $affsettingarr['product_id'])) -> order('total desc') -> sum('total');
			}else{
				$maxOrderTotal = $this->saledb -> where(array('pay_status' => 1, 'member_id' => $this->member_id, 'product_id' => $affsettingarr['product_id'])) -> order('total desc') -> getField('total');
			}
	    }else{
			
			if($affsettingarr['totalsumtype'] == 1){
				$maxOrderTotal = $this->saledb -> where(array('pay_status' => 1, 'member_id' => $this->member_id)) -> order('total desc') -> sum('total');
			}else{
				$maxOrderTotal = $this->saledb -> where(array('pay_status' => 1, 'member_id' => $this->member_id)) -> order('total desc') -> getField('total');
			}
		
		}
		//最高的一次性消费金额
		
		
		//升级为其它等级
		//计算直推人数
		//计算八级以内市场人数
		//$affCount_ = $this->memberdb -> getLevel1Count($memberInfo['id'], 1, 8);
		//开始升级
		
		foreach(array_reverse($affsettingarr['levelbuy']) as $k => $v){
			
			$productex = M('Sale') -> where(array('product_id' => $v, 'pay_status' => 1)) -> find();
			if($productex && $v > 0){
				$rlevel[0] = $k + 2;
			}
		}
		
		
		
		
		
		
		
		
		
		if($mylevel > 0){
			
			$mylevel1 = 1;
			
			
			
			foreach(array_reverse($affsettingarr['levelaff']) as $k => $v){
				$affCount = M('Member_member') -> where(array('member_id' => $memberInfo['id'], 'deep' => 1, 'level' => $mylevel1)) -> count();
				if($affCount >= $v){
					$rlevel[1] = $k + 2;
					
					//$curlevel = $k + 2;
				}$mylevel1 ++ ;
				//$affCount = M('Member_member') -> where(array('member_id' => $memberInfo['id'], 'deep' => 1, 'level' => $curlevel)) -> count();
			}
		}
			
			
		
		//dump($rlevel);
		//平级多少人以后也能升级
		
		
		
		/*foreach(array_reverse($affsettingarr['levelaff_']) as $k => $v){
			if($affCount_ >= $v){
				$rlevel[2] = $k + 2;
			}
		}*/
		
		
		//dump($rlevel); 
		if($affsettingarr['levelupand'] == 1){
			$retlevel = min($rlevel);
		}else{
			$retlevel = max($rlevel);
		}
		//dump($retlevel);
		$data['level'] = $retlevel > 0? $retlevel : $mylevel;
		
		//dump($data);
		//if($memberInfo['level'] < $data['level']){
			//如果强制不降级就取消
			//if(__SITEID__ == 13){dump($data['level']);}
			if($data['level'] < $memberInfo['level'] && $memberInfo['leveldown'] == 0){
				$data['level'] = $memberInfo['level'];
			}
			$ret = $this->memberdb -> where(array('id' => $memberInfo['id'])) -> data($data) -> save();//dump($ret);
			if($ret != 0 && $memberInfo['level'] < $data['level']){
				$this -> affsettingarr['VIPaff'] = 0;
				sendWXMsg($memberInfo['openid'], str_replace('@levelname@', $this->getLevelName(), $affsettingarr['changelevel']));
			}
			//echo $this->memberdb -> getLastSql();
			$mtmdb = M('Member_member');
			$mtmdb -> where(array('smember_id' => $memberInfo['id'])) -> data($data) -> save();
		//}
	}
	
	//获取等级名称
	public function getLevelName(){
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$namelist = $this -> affsettingarr['levelname'];
		$namelist[] = $this -> affsettingarr['levelnamebase'];
		$namelist[] = '普通会员';
		$namelist = array_reverse($namelist);
		return $namelist[$memberInfo['level']];
	}
	
	//获取等级名称列表
	public function getLevelNameList(){
		$memberInfo = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$namelist = $this -> affsettingarr['levelname'];
		$namelist[] = $this -> affsettingarr['levelnamebase'];
		$namelist[] = '普通会员';
		$namelist = array_reverse($namelist);
		return $namelist;
	}
	
	//获取父子级会员数组8级
	public function getUserArr($pid=0,$arr=array(), $deep = 0){
		$re=$this->memberdb->where(array('id'=>$pid,'site_id'=>$this->site_id))->find();
		if($_GET['dump']){dump($this -> affsettingarr['VIPaff']);}
			if($this -> affsettingarr['VIPaff'] == 1 && $deep == 0){
				$member = $this->memberdb -> where(array('id'=>$this->member_id,'site_id'=>$this->site_id)) -> find();
				
				if($member['level'] > 0){
					$re = $member;
				}
			}
		//8级返回
		if($deep == 8){return $arr;}
		if(!is_array($re)){
			return $arr;
		}else{
			$re['deep'] = $deep + 1;
			//if($re['level'] > 0){
			    $arr[]=$re;
			//}
			$deep ++;
			return $this->getUserArr($re['pid'],$arr, $deep);
		}
	}
	
	//获取父子级会员数组无限级
	public function getUserArrAll($pid=0,$arr=array(), $deep = 0){
		$re=$this->memberdb->where(array('id'=>$pid,'site_id'=>$this->site_id))->find();
		
		
		
		if($this -> affsettingarr['VIPaff'] == 1 && $deep == 0){
			$member = $this->memberdb -> where(array('id'=>$this->member_id,'site_id'=>$this->site_id)) -> find();
			
			if($member['level'] > 1){
				$re = $member;
			}
		}
		
		
		if(!is_array($re)){
			return $arr;
		}else{
			if($re['level'] > 1){
				$re['deep'] = $deep + 1;
			    $arr[]=$re;
			}
			$deep ++;
			
			
			return $this->getUserArrAll($re['pid'],$arr, $deep);
		}
	}
	
	
	
	
	//获取VIP分成用户列表(需要分成的用户列表)
	public function getuserlist(){
		$ordermember = $this->memberdb -> where(array('id' => $this->order['member_id'])) -> find();
		
		$affsettingarr = $this -> affsettingarr;
		
		$list = $this -> getUserArr($ordermember['pid']);
		
		$prevaff = 0;
		foreach($list as $k => $v){
			
			
			if($affsettingarr['VIPaff'] == 1 && $ordermember['level'] > 0 && $k == 0){
				$list[$k]['aff'] = $affsettingarr['level'][$k];
				continue;
			}
			
			
			
			
			
			if($v['level'] > 0 && $v['level'] >= $ordermember['level']){
				
				
				
				
				
				
				
				switch($v['level']){
					case 2 : $levelkey = 'xlevel'; break;
					case 3 : $levelkey = 'clevel'; break;
					case 4 : $levelkey = 'plevel'; break;
					case 5 : $levelkey = 'glevel'; break;
					default : $levelkey = 'level';
				}
				
			    $list[$k]['aff'] = $affsettingarr[$levelkey][$k];
			}else{
				$list[$k]['aff'] = 0;
			}
		}
		return $list;
	}
	
	//获取总代分成总额
	public function getuserlistAll(){
		$ret = array();
		$ordermember = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$list = $this -> getUserArrAll($ordermember['pid']);
		$affList = array_reverse($this->affsettingarr['rlevel']);//dump($affList);
		foreach($list as $k => $v){
			
			if($k == 0){
				$aff = $affList[$v['level']-2];
			}else{
				$aff = $affList[$v['level']-2] - $affList[$list[$k - 1]['level']-2];
			}
			if($aff > 0){
			    $list[$k]['aff'] = $aff;
				
				$ret[] = $list[$k];
			}
			//$list[$k]['aff'] = $affList[$v['level']-2];
		}
		return $ret;
	}
	
	
	//下单提醒（当前未付款）
	public function sendMsg(){
		
		$thismember = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		
		
		$db = M('Affiliatelog');
		$productList = $this->getmoney();
		$userList = $this->getuserlistAll();
		$userList1 = $this->getuserlist();
		$domain = C('DOMAIN_MAIN');
		$picurl = 'http://'.$domain[0].'/Public'.M('Product') -> where(array('id' => $productList[0]['product_id'])) -> getField('img_url');
		//往上发送信息
		foreach($userList as $k => $v){
			$money = 0;
			foreach($productList as $key => $val){
				$map['type'] = 1;
				$map['member_id'] = $v['id'];
				$map['order_id'] = $this->order['id'];
				$map['product_id'] = $val['product_id'];
				if($db -> where($map) -> find()){
					continue;
				}
				
				
				//写入日志，以便以后统计，注意这里不是写账户日志
				$data['site_id'] = $this->order['site_id'];
				$data['member_id'] = $v['id'];
				$data['datetime'] = time();
				$data['type'] = 1;
				$data['order_id'] = $this->order['id'];
				$data['aff_money'] = round($val['aff_money']*$v['aff']/100,2);
				$data['product_id'] = $val['product_id'];
				if($data['aff_money'] > 0){
					$money += $data['aff_money'];
					$db -> data($data) -> add();
				}
			}
			if($money > 0){
				//信息通知
				$sendWXNews[0]['title'] = '会员下单通知';
				$sendWXNews[0]['url'] = '';
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，会员付款后您将得到分成金额为：'.$money;
				sendWXNews($v['openid'], $sendWXNews);
			}
		}
		
		foreach($userList1 as $k => $v){
			$money = 0;
			foreach($productList as $key => $val){
				$map['type'] = 0;
				$map['member_id'] = $v['id'];
				$map['order_id'] = $this->order['id']; 
				$map['product_id'] = $val['product_id'];
				if($db -> where($map) -> find()){
					continue;
				}
				//写入日志，以便以后统计，注意这里不是写账户日志
				$data['site_id'] = $this->order['site_id'];
				$data['member_id'] = $v['id'];
				$data['datetime'] = time();
				$data['order_id'] = $this->order['id'];
				$data['aff_money'] = round($val['aff_money']*$v['aff']/100,2);
				$data['product_id'] = $val['product_id'];
				if($data['aff_money'] > 0){
					$money += $data['aff_money'];
					$db -> data($data) -> add();
				}
			}
			if($money > 0){ 
				//信息通知
				$sendWXNews[0]['title'] = '会员下单通知';
				$sendWXNews[0]['url'] = '';
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，会员付款后您将得到分成金额为：'.$money;
				sendWXNews($v['openid'], $sendWXNews);
			}
		}
	}
	
	//写入分成日志
	
	public function insertlogAll(){
		
		
		
		
		
		
		
		$thismember = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$db = M('Member_account_log');
		$productList = $this->getmoney();
		$userList = $this->getuserlistAll();
		$domain = C('DOMAIN_MAIN');
		$picurl = 'http://'.$domain[0].'/Public'.M('Product') -> where(array('id' => $productList[0]['product_id'])) -> getField('img_url');
		foreach($userList as $k => $v){
			$money = 0;
			foreach($productList as $key => $val){
				
				$map['type'] = 1;
				$map['member_id'] = $v['id'];
				$map['order_id'] = $this->order['id'];
				$map['product_id'] = $val['product_id'];
				$map['attr'] = $val['attr'];
				if($db -> where($map) -> find()){
					continue;
				}
				
				
				$data['type'] = 1;
				$data['member_id'] = $v['id'];
				$data['user_id'] = 0;
				$data['pdstate'] = 3; //类型3为分成
				$data['dateline'] = time();
				
				$data['deep'] = $v['deep'];
				$data['affmoney'] = $val['aff_money'];
				
				$data['changenum'] = round($val['aff_money']*$v['aff']/100,2);
				$data['order_id'] = $this->order['id'];
				$data['order_sn'] = $this->order['ordernumber'];
				$data['product_id'] = $val['product_id'];
				$data['num'] = $val['num'];
				$data['site_id'] = $this->site_id;
				$data['attr'] = $val['attr'];
				$data['remark'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$data['changenum'];
				$data['goodsMoney'] = $val['total'];
				if($data['changenum'] > 0){
					$money += $data['changenum'];
					
					//是否需要审核分成
					$flag = false;
					if($val['affpass'] > 0){
						$hbcount = ceil($data['changenum'] / 200);
						$hbmoney = $data['changenum'];
						for($i = 0; $i < $hbcount; $i++){
							$sendmoney = 200;
							if($hbmoney > 200){
							    $hbmoney = $hbmoney - 200;
							}else{
								$sendmoney = $hbmoney;
							}
							//dump($sendmoney);
							$result = sendBonus($v['openid'],$sendmoney,$this->site_id);
						}
						//exit;
					}
					
					$db -> data($data) -> add();
				}
			}
			if($money > 0){
				//信息通知
				$sendWXNews[0]['title'] = '订单支付通知';
				$sendWXNews[0]['url'] = '';
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				//$msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				sendWXNews($v['openid'], $sendWXNews);
			}
		}
	}
	
	
	//获取等级价格
	public function getPriceByLevel($product_id, $level){
		$product = M('Product') -> where(array('id' => $product_id)) -> find();
		$levelpriceconfig = unserialize($product['levelpriceconfig']);
		if($levelpriceconfig){
			foreach($levelpriceconfig as $lk => $lv){
				if($level == $lv['levelkey'] && (float)$lv['levelprice'] > 0){
					$price = (float)$lv['levelprice'];
				}
			}
			return $price;
		}
		return 0;
	}
	
	public function insertlog(){
		$thismember = $this->memberdb -> where(array('id' => $this->member_id)) -> find();
		$db = M('Affiliatelog');
		$db -> where(array('order_id' => $this->order['id'])) -> delete();
		$db = M('Member_account_log');
		$productList = $this->getmoney();
		$userList = $this->getuserlist();
		$domain = C('DOMAIN_MAIN');
		$picurl = 'http://'.$domain[0].'/Public'.M('Product') -> where(array('id' => $productList[0]['product_id'])) -> getField('img_url');
		
		
		
		
		
		
		
		$prevaffmoney = 0;
		foreach($userList as $k => $v){
			$money = 0;
			
			foreach($productList as $key => $val){
				
				$map['type'] = 0;
				$map['member_id'] = $v['id'];
				$map['order_id'] = $this->order['id'];
				$map['product_id'] = $val['product_id'];
				$map['attr'] = $val['attr'];
				if($db -> where($map) -> find()){
					continue;
				}
				
				
				$data['deep'] = $v['deep'];
				$data['affmoney'] = $val['aff_money'];
				
				$data['type'] = 0;
				$data['member_id'] = $v['id'];
				$data['user_id'] = 0;
				$data['pdstate'] = 3; //类型3为分成
				$data['dateline'] = time();
				if($k == 0){$prevmember = $thismember;}
				$levelPrice = $this->getPriceByLevel($val['product_id'], $v['level']);
				$curprice = $this->getPriceByLevel($val['product_id'], $prevmember['level']);
				$changenum = $curprice - $levelPrice;
				
				
				//dump($levelPrice .'--'. $curprice);
				if($levelPrice > 0 && $changenum > 0){
					$prevaffmoney = $levelPrice;
					$prevmember = $userList[$k];
					$data['changenum'] = $changenum * $val['num'];
				}else{
					$data['changenum'] = round($val['aff_money']*$v['aff']/100,2);
				}
				
				
				
				$data['order_id'] = $this->order['id'];
				$data['order_sn'] = $this->order['ordernumber'];
				$data['product_id'] = $val['product_id'];
				$data['num'] = $val['num'];
				$data['site_id'] = $this->site_id;
				$data['attr'] = $val['attr'];
				$data['remark'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$data['changenum'];
				$data['goodsMoney'] = $val['total'];
				if($data['changenum'] > 0){
					$money += $data['changenum'];
					//是否需要审核分成
					$flag = false;
					if($val['affpass'] > 0){
						$hbcount = ceil($data['changenum'] / 200);
						$hbmoney = $data['changenum'];
						for($i = 0; $i < $hbcount; $i++){
							$sendmoney = 200;
							if($hbmoney > 200){
							    $hbmoney = $hbmoney - 200;
							}else{
								$sendmoney = $hbmoney;
							}
							//dump($sendmoney);
							$result = sendBonus($v['openid'],$sendmoney,$this->site_id);
						}
						//exit;
					}
					$db -> data($data) -> add();
				}
			}
			if($money > 0){
				//信息通知
				$sendWXNews[0]['title'] = '订单支付通知';
				$sendWXNews[0]['url'] = '';
				$sendWXNews[0]['picurl'] = $picurl;
				$sendWXNews[0]['description'] = '【'.$thismember['nickname'].'】下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				//$msg = '粉丝下单，订单号为：'.$this->order['ordernumber'].'，分成金额为：'.$money;
				sendWXNews($v['openid'], $sendWXNews);
			}
		}
		//总代分成写入
		//$this->insertlogAll();
	}
	
	//撤消一个分成
	public function loggoback(){
		
	}
	
	//获取分成总额
	public function getmoney(){
		return $this -> saledb -> where(array('order_id' => $this->order['id'])) -> Field('(aff_money*num) as aff_money,product_id,price,total,num,attr,affpass') -> select();
	}
	
	//返回错误信息
	public function getError(){
		return $this->error['info'];
	}
	
	
	public function getAffData(){
		$db = M('Member_account_log');
		$levelname = $this -> getLevelName();
		
		
		$level = M('Member') -> where(array('id' => $this->member_id)) -> getField('level');
		//if(isset($_GET['dump'])){echo $level;dump($this->member_id);}
		$ret = array();
		if($level > 1){ 
			
		    $data = $db -> where(array('member_id' => $this->member_id, 'site_id' => $this->site_id, 'type' => 1, 'pdstate' => 3, 'order_id' => array('gt',0))) -> Field('count(*) as orderCount, sum(changenum) as orderAffMoney, sum(goodsMoney) as orderTotal') -> select();
			//dump($db -> getLastSql());
			$ret[0]['levelname'] = $levelname;
			//级差订单数量
			$ret[0]['orderCount'] = (int)$data[0]['orderCount'];
			//级差订单总额
			$ret[0]['orderTotal'] = (float)$data[0]['orderTotal'];
			//级差订单分成
			$ret[0]['orderAffMoney'] = (float)$data[0]['orderAffMoney'];
			
			$ret[0]['type'] = 1; 
		}
		
		 
		if($level > 0){
			$data = $db -> where(array('member_id' => $this->member_id, 'site_id' => $this->site_id, 'type' => 0, 'pdstate' => 3, 'order_id' => array('gt',0))) -> Field('count(*) as orderCount, sum(changenum) as orderAffMoney, sum(goodsMoney) as orderTotal') -> select();
			
			$ret[1]['levelname'] = $this -> affsettingarr['levelnamebase'];
			//VIP订单数量
			$ret[1]['orderCount'] = (int)$data[0]['orderCount'];
			//VIP订单总额
			$ret[1]['orderTotal'] = (float)$data[0]['orderTotal'];
			//VIP订单分成
			$ret[1]['orderAffMoney'] = (float)$data[0]['orderAffMoney'];
			$ret[1]['type'] = 0;
		}
		return $ret;
	}
	
}